package com.lfz.search.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lfz.common.exception.MsgException;
import com.lfz.search.pojo.JobItem;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.lfz.search.config.Constant.MAPPER;


@Service
public class JobItemService {

    @Autowired
    private TransportClient client;

    public void addDocument(JobItem jobItem) throws MsgException {

        // 添加或更新文档
        try {
            // 将Java对象转成JSON字符串
            String docString = MAPPER.writeValueAsString(jobItem);

            IndexResponse response = client.prepareIndex(
                    /*索引名称*/ "job_item",
                    /*文档类型*/ "job_item",
                    /*文档ID*/ jobItem.getJobId()).setSource(
                    /*文档内容json字符串*/ docString,
                    /*文档内容类型*/ XContentType.JSON).execute().actionGet();
            // 如果文档不存在，则创建，成功返回"CREATED"
            // 如果文档存在，则更新，成功返回"OK"
            System.out.println(response.status());
        } catch (ActionRequestValidationException | JsonProcessingException e) {
            e.printStackTrace();
            throw new MsgException("索引添加失败！");
        }
    }


}
